import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import play.*;
import play.db.jpa.Blob;
import play.db.jpa.Model;
import play.jobs.*;
import play.libs.MimeTypes;
import play.test.*;

import models.*;

@OnApplicationStart
public class Bootstrap extends Job{
	
	public void doJob(){
		
		//checks if database is empty and loads initial data
		if (Admin.count() == 0) {
			Fixtures.loadModels("apts_users.yml");
		}
		
		if (Event.count()==0) {
			Fixtures.loadModels("apts_events.yml");
			
			List<Event> events = Event.findAll();
			for (Event event : events) {
				event.picture = new Blob();
				try {
					event.picture.set(new FileInputStream("public/images/events/" + event.name + ".jpg"), MimeTypes.getContentType("public/images/events/" + event.name + ".jpg"));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				event.save();
			}
		}

		if (Offer.count()==0) {
			Fixtures.loadModels("apts_offers.yml");
			
			List<Offer> offers = Offer.findAll();
			for (Offer offer : offers) {
				offer.picture = new Blob();
				try {
					offer.picture.set(new FileInputStream("public/images/offers/" + offer.event.name + " " + offer.street + ".jpg"), MimeTypes.getContentType("public/images/offers/" + offer.event.name + " " + offer.street + ".jpg"));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				offer.save();
			}
		}
	}

}
